import type { FormInstance } from 'element-plus'
import type { TemplateItemType, TemplatePropsType } from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElRow,
  ElCol,
  ElButton,
  ElIcon,
  ElMessage,
  ElRadioGroup,
  ElRadio
} from 'element-plus'
import { EditPen } from '@element-plus/icons-vue'
import { GUTTER, SPAN_STYLE_DOUBLE } from '~/utils/const'

export default defineComponent({
  name: 'SystemUserOptions',
  props: ['visible', 'type', 'record'],
  emits: ['cancel'],
  setup(props: TemplatePropsType, { emit }) {
    const store = useStore()
    const ruleFormRef = ref<FormInstance>()
    const formValues = reactive<TemplateItemType>({})
    const state = reactive({
      templateTypeOpt: [
        { id: 1, title: '短信' },
        { id: 2, title: '邮件' },
        { id: 3, title: '微信' }
      ]
    })
    const title = { add: '新增', update: '编辑', read: '查看' }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 提交表单
    const handleSubmitForm = () => {
      const { type } = props
      if (!ruleFormRef.value) return
      ruleFormRef.value.validate(async (valid) => {
        if (!valid) return
        const params = { ...formValues }

        const res = await store.dispatch(
          type === 'add' ? 'template/TemplateListPost' : 'template/TemplateUpdatePost',
          params
        )
        if (res?.code === 200) {
          ElMessage({ type: 'success', message: '操作成功' })
          handleCloseModal()
        }
      })
    }

    onMounted(() => {
      const { type } = props
      if (props.record?.id) {
        Object.assign(
          formValues,
          type === 'update'
            ? {
                id: props.record?.id,
                templateContent: props.record?.templateContent,
                templateName: props.record?.templateName,
                templateType: props.record?.templateType,
                useStatus: props.record?.useStatus
              }
            : props.record
        )
      }
    })

    return () => {
      const { type, visible } = props
      return (
        <ElDialog
          title={(title[type] as string) || '查看'}
          modelValue={visible}
          closeOnClickModal={false} // 点遮罩层不关弹窗
          draggable // 可拖拽
          beforeClose={handleCloseModal}
          v-slots={
            type !== 'read' && {
              footer: () => (
                <>
                  <ElButton type="primary" onClick={handleSubmitForm}>
                    <ElIcon>
                      <EditPen />
                    </ElIcon>
                    &nbsp; {type === 'add' ? '保存' : '修改'}
                  </ElButton>
                  <ElButton onClick={handleCloseModal}>取消</ElButton>
                </>
              )
            }
          }
        >
          <ElForm label-width="100px" ref={ruleFormRef} model={formValues}>
            <ElRow gutter={GUTTER}>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="templateContent"
                  label="模版内容"
                  rules={[{ required: true, message: '请输入模版内容' }]}
                >
                  {type === 'read' ? (
                    formValues.templateContent
                  ) : (
                    <ElInput v-model={formValues.templateContent} placeholder="请输入模版内容" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="templateName"
                  label="模板标题"
                  rules={[{ required: true, message: '请输入模板标题' }]}
                >
                  {type === 'read' ? (
                    formValues.templateName
                  ) : (
                    <ElInput v-model={formValues.templateName} placeholder="请输入模板标题" />
                  )}
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="templateType"
                  label="模板类型"
                  rules={[{ required: true, message: '请输入模板类型' }]}
                >
                  <ElSelect v-model={formValues.templateType} placeholder="请输入模板类型">
                    {state.templateTypeOpt?.map((item: any) => (
                      <ElOption key={item?.id} value={item?.id!} label={item?.title} />
                    ))}
                  </ElSelect>
                </ElFormItem>
              </ElCol>
              <ElCol {...SPAN_STYLE_DOUBLE}>
                <ElFormItem
                  prop="useStatus"
                  label="是否使用"
                  rules={[{ required: true, message: '请输入是否使用' }]}
                >
                  <ElRadioGroup v-model={formValues.useStatus}>
                    {[
                      { id: '0', name: '否' },
                      { id: '1', name: '是' }
                    ]?.map((item: any) => (
                      <ElRadio label={item.id}>{item.name}</ElRadio>
                    ))}
                  </ElRadioGroup>
                </ElFormItem>
              </ElCol>
            </ElRow>
          </ElForm>
        </ElDialog>
      )
    }
  }
})
